<template>
    <!-- 新增编辑弹窗 -->
    <el-dialog v-model="dialogUserRole" @close="cancel" width="1000px">
      <template #header>
        <div class="header-title">新建账单</div>
      </template>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="90px">
        <el-row class="marginTop10">
          <el-col :span="8">
            <el-form-item label="账单类型" prop="billType">
              <el-select v-model="form.billType" placeholder="请选择">
                <el-option v-for="item in billTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.billCnyAmount">
            <el-form-item :label="settlementDirection==1 ? '应收金额':'应付金额'" prop="billCnyAmount">
              <el-input type='number' v-model.trim="form.billCnyAmount" disabled="true" placeholder="请输入金额" maxlength="20">
                <template #append>¥</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.billUsdAmount">
            <el-form-item :label="settlementDirection==1 ? '应收金额':'应付金额'" prop="billUsdAmount">
              <el-input type='number' v-model.trim="form.billUsdAmount" disabled="true" placeholder="请输入金额" maxlength="20">
                <template #append>$</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="8">
            <el-form-item label="折算币种" prop="conversionCurrency">
              <el-select @change="conversionCurrencyChang" v-model.trim="form.conversionCurrency" placeholder="请选择">
                <el-option v-for="item in feeCurrencyList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折算汇率" prop="rate">
              <template v-if="form.conversionCurrency == 'USD'">
                  <el-input @change="rateChang"  v-model.trim="form.rate" :formatter="formatterNumberFee" placeholder="请输入折算汇率" maxlength="20" >
                    <template #prefix>1美元=</template>
                    <template #append>人民币</template>
                  </el-input>
              </template>
              <template v-else>
                <el-input @change="rateChang"  v-model.trim="form.rate" :formatter="formatterNumberFee" placeholder="请输入折算汇率" maxlength="20" >
                    <template #prefix>1人民币=</template>
                    <template #append>美元</template>
                  </el-input>
              </template>
              
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折算金额" prop="conversionAmount">
              <el-input type='number' v-model.trim="form.conversionAmount" disabled="true" placeholder="请输入折算金额" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="marginTop10">
          <el-col :span="24">
            <el-form-item class="file" label="附件" prop="billUrl" style="width: 100%;">     
              <!-- <uploadFile ref="uploadFileRef" :fileList="detailFileList" :type="'pdf_jpg_png'" :limit="10" :multiple="true"></uploadFile> -->
              <UploadFilesImages ref="uploadFileRef" :urlList="detailFileList" :limit="10" :fileSize="3" :showNumber="'6'" :drag="true" :displayType="'2'" :type="'pdf/doc/docx/xls/xlsx/jpg/jpeg/png/zip'" @updateInfo="updateInfo"></UploadFilesImages>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="marginTop10"> 
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input  v-model.trim="form.remark" placeholder="请输入备注" :formatter="containsEmoji" show-word-limit type="textarea" maxlength="100" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
            <el-button type="primary" @click="submitForm(formRef)">保存</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted,toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue'
import { addBill } from '@/api/financial/bills'
import { getFeeDetailsListAmountSum } from '@/api/financial/operatingInfo'
import { formatterNumberFee,formatterNumber,containsEmoji} from '@/utils'

import uploadFile from '@/components/upload/index.vue'
import UploadFilesImages from '@/components/upload/uploadFiles-Images'
import type { FormInstance, FormRules } from 'element-plus'
const feeCurrencyList = ref([
  {
    value:'CNY',
    label:'¥'
  },
  {
    value:'USD',
    label:'$'
  },
])
const billTypeList = ref([
  { label: '业务账单', value: 5 },
  { label: '超期费账单', value: 10},
  { label: '堆存费账单', value: 15},
  { label: '堆场超期费账单', value: 20},
  { label: '其他', value: 25}
])

const formRef = ref()
const dialogUserRole = ref(false) //弹框
const detailFileList = ref([])
const ids = ref([])
const data = reactive({
  form: {
    billType:5,
    conversionCurrency:'CNY',
    billCnyAmount:0,
    billUsdAmount:0,
  },
  rules: {
    billType: [{ required: true, message: "账单类型不能为空", trigger: "blur" }],
    billCnyAmount: [{ required: true, message: "应收金额不能为空", trigger: "blur" }],
    billUsdAmount: [{ required: true, message: "应收金额不能为空", trigger: "blur" }],
    // rate: [{ required: true, message: "折算汇率不能为空", trigger: "blur" }],
    // conversionCurrency: [{ required: true, message: "折算币种不能为空", trigger: "blur" }],
    // conversionAmount: [{ required: true, message: "折算金额不能为空", trigger: "blur" }],
  }
});
const { form, rules } = toRefs(data);
const settlementDirection = ref(1)
const onShow = async (row,type,settlement) => {
  dialogUserRole.value = true 
  ids.value=row 
  settlementDirection.value=settlement

  // if(type == 1){
  //   //1业务账单  2堆存费账单
  //   billTypeList.value=[ {
  //     value:5,
  //     label:'业务账单'
  //   },
  //   {
  //     value:10,
  //     label:'超期费账单'
  //   },]
  //   form.value.billType=5
  // }else if(type == 2){
  //    //1业务账单  2堆存费账单
  //   billTypeList.value=[{
  //     value:15,
  //     label:'堆存费账单'
  //   },
  //   {
  //     value:20,
  //     label:'堆存超期费账单'
  //   },]
  //   form.value.billType=15
  // }
  getFeeDetailsListAmountSumData(row)
}
const rateChang = (row)=>{  // 修改汇率时重新计算 应收金额
  if(/^[+-]?\d+(\.\d+)?$/.test(row)){ //判断是数字
    if(row ==0 ) return ElMessage.warning('请输入数字并且不能为0');

    let amount:number
    if(form.value.conversionCurrency=='CNY'){
      amount = Number(form.value.billUsdAmount) * Number(form.value.rate) + Number(form.value.billCnyAmount)
    }else if(form.value.conversionCurrency=='USD'){
      amount = Number(form.value.billCnyAmount) / Number(form.value.rate) + Number(form.value.billUsdAmount)
    }
    form.value.conversionAmount=parseFloat(amount.toFixed(2))
  }else{
      ElMessage.warning('请输入数字并且不能为0');
  }
}
const conversionCurrencyChang = () => { // 修改币种时重新计算 应收金额
  if(form.value?.rate){
    if(form.value?.rate==0){
      ElMessage.warning('折算汇率不能为0');
      return false
    }
    let amount:number
    if(form.value.conversionCurrency=='CNY'){
      amount = Number(form.value.billUsdAmount) * Number(form.value.rate) + Number(form.value.billCnyAmount)
    }else if(form.value.conversionCurrency=='USD'){
      amount = Number(form.value.billCnyAmount) / Number(form.value.rate) + Number(form.value.billUsdAmount)
    }
    form.value.conversionAmount=parseFloat(amount.toFixed(2))
  }
}
const uploadFileRef=ref()
const emits = defineEmits(['addModal'])

/** 提交按钮 */
const submitForm = (formEl: FormInstance | undefined) =>{
  if (!formEl) return
  formEl.validate(valid => {  
    let dataForm = JSON.parse(JSON.stringify(form.value))
    let fileList = uploadFileRef.value.resultList || []
        dataForm.billUrl=JSON.stringify(fileList) //附件
    if (valid) {
      dataForm.ids=ids.value
      addBill(dataForm).then(response => {
        ElMessage.success('保存成功');
        emits('addModal');
        cancel();
      });
    }
  });
};
//查询费用合计
const getFeeDetailsListAmountSumData = (row)=>{
  let data={ids:row}
  getFeeDetailsListAmountSum(data).then(res => {
    form.value.billCnyAmount = res.data.deductAmountCnySum
    form.value.billUsdAmount = res.data.deductAmountUsdSum
  })
}
//关闭弹框
const cancel = () => {
  formRef.value.resetFields()// 重置数据
  ids.value=[]
  detailFileList.value=[]
  dialogUserRole.value=false
}

const updateInfo = (row) =>{
  detailFileList.value = row

  console.log(row)
}

defineExpose({ onShow })

</script>

<style scoped>
.choose-item-2 {
  margin-left: 20px;
}
.stust{
  padding:0 20px;
}
.choose-item-3 {
  display: block;
  margin-left: 20px;
}
.main-cent{
  padding: 0 10px;
}
.input-sel {
  border: 1px solid #C0C4CC; 
  border-radius: 4px;
  overflow: hidden;

}
.input-sel :deep(.el-input__wrapper) {
  box-shadow: none !important; /* 去掉阴影 */
  border-radius: 0; /* 去掉圆角 */
  border-left: 1px solid #C0C4CC; /* 默认下边框颜色 */
}
.input-sel :deep(.el-select__wrapper) {
  box-shadow: none !important; /* 去掉阴影 */
  border-radius: 0; 
}
.header-title{
  border-left: 4px solid #2158F3;
  padding-left: 8px;
  line-height: 18px;
}
.file :deep(.el-form-item__content){
  display: block;
}
</style>